"""
Author: runyu.ma

flatten_loop_pass.py
"""

from ..core.dslc_parser import ASTNode, Identifier, BlockOp


def merge_if_cond_pass(top: ASTNode):
    if isinstance(top, Identifier) and top.name == 'if':
        return 2
    return 0


#先合并if，如果是else if的话就变成了
#Identifier(else) BlockOp([Identifier(if) BlockOp(cond) BlockOp(body)])
#这样的话只需要merge一个，然后在pass中再合并
def merge_else_cond_pass(top: ASTNode):
    if isinstance(top, Identifier) and top.name == 'else':
        return 1
    return 0


def is_else_if_keyword(top: ASTNode):
    '''判断是不是else if，将else if合并成一个'''
    if isinstance(top, BlockOp) and len(top.oplist) == 2:
        if not isinstance(top.oplist[0], Identifier):
            return False
        if not top.oplist[0].name == 'else':
            return False
        iftop = top.oplist[1]
        if isinstance(iftop, BlockOp) and len(iftop.oplist) == 3:
            if not isinstance(iftop.oplist[0], Identifier):
                return False
            if not iftop.oplist[0].name == 'if':
                return False
            return True
    return False


def merge_else_if_keyword_pass(_, top: ASTNode):
    '''合并'''
    oplist = []
    oplist.append(Identifier('else if'))
    oplist.append(top.oplist[1].oplist[1])
    oplist.append(top.oplist[1].oplist[2])
    return BlockOp(oplist)
